from pathlib import Path
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox, LTTextLine
# pdfminer3k解析pdf文本  https://blog.csdn.net/leviopku/article/details/86443426
import re
import pandas as pd

# 先提取转换到txt文件中，然后逐行读取，转换出需要的药性等


def read_zhongyao_pdf(path):
    fp = open(path, 'rb')
    parser = PDFParser(fp)
    doc = PDFDocument()
    parser.set_document(doc)
    doc.set_parser(parser)
    doc.initialize('')
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    laparams.char_margin = 1.0
    laparams.word_margin = 1.0
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    extracted_text = ''

    for page in doc.get_pages():
        interpreter.process_page(page)
        layout = device.get_result()
        for lt_obj in layout:
            if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
                extracted_text += lt_obj.get_text()
                line_text = lt_obj.get_text()
                if(re.match(r'[A-Z].*', line_text)):
                    print("first_text:"+first_text)
                    print("match-line:"+line_text)
                if(re.match(r'【(药性|功效).*', line_text)):
                    print("match-line:"+line_text)
                first_text = line_text
                print(first_text)
    with open('convertedFile.txt', "wb") as txt_file:
        txt_file.write(extracted_text.encode("utf-8"))


def read_fangji_pdf(path):
    fp = open(path, 'rb')
    parser = PDFParser(fp)
    doc = PDFDocument()
    parser.set_document(doc)
    doc.set_parser(parser)
    doc.initialize('')
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    laparams.char_margin = 1.0
    laparams.word_margin = 1.0
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    extracted_text = ''
    all_extracted_text = ''
    start_flag = False
    end_flag = False
    for page in doc.get_pages():
        interpreter.process_page(page)
        layout = device.get_result()
        for lt_obj in layout:
            if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
                line_text = lt_obj.get_text()
                all_extracted_text += line_text
                if(re.match(r'麻黄汤', line_text)):
                    start_flag = True
                if(re.match(r'内补黄芪汤', line_text)):
                    end_flag = True

                if(start_flag):
                    if(re.match(r'第.*', line_text)):
                        continue
                    print(line_text)
                    extracted_text += line_text
                if(end_flag):
                    print(line_text)
                    # with open('fangjilist.txt', "wb") as txt_file:
                    #     txt_file.write(extracted_text.encode("utf-8"))
                    #     txt_file.close
                    # 使用异常跳出整个循环
                    # raise StopIteration

                #     print("first_text:"+first_text)
                #     print("match-line:"+line_text)
                # if(re.match(r'【(药性|功效).*', line_text)):
                #     print("match-line:"+line_text)
                # first_text = line_text
                # print(first_text)
    with open('fangjixue.txt', "wb") as txt_file:
        txt_file.write(all_extracted_text.encode("utf-8"))


def read_zhongyao_txt_file(path):
    with open(path, 'r') as txt_file:
        first_text = ""
        line_text = txt_file.readline()
        list = []
        name = ""
        desc = ""
        function = ""
        source = ""
        while line_text:
            match = re.match(r'^[A-Z].*(《.*》).*）$', line_text)
            if(match):
                name = first_text.replace("	", "").replace("　", "")
                source = match.group(1)
                print("first_text:"+name)
                print("match-line:"+source)
            if(re.match(r'【药性.*', line_text)):
                desc = line_text
                print("match-line:"+desc)
            if(re.match(r'【功效.*', line_text)):
                function = line_text
                print("match-line:"+line_text)
                # 功效后就直接拼接
                list.append({
                    "name": name,
                    "desc": desc,
                    "function": function,
                    "source": source
                })
            first_text = line_text
            line_text = txt_file.readline()

            # print(first_text)
        print("detail: %s" % list[0])
        # dataframe写入到excel表格

        df = pd.DataFrame(list)
        df.to_excel("zhongyao.xlsx")


def read_fangjixue_txt():
    fangji_set = set()
    with open("fangjilist.txt", "r") as fangjilist:
        line = fangjilist.readline()
        while line:
            fangji_set.add(line)
            line = fangjilist.readline()

    with open("fangjixue.txt", "r") as fangjifile:
        line = fangjifile.readline()
        startFlag = False
        endFlag = False
        fangji = {
            "name": "",
            "source": "",
            "detail": "",
            "use": "",
            "function": "",
            "fix": ""
        }
        name = ""
        source = ""
        detail = ""
        use = ""
        function = ""
        fix = ""
        list = []
        while line:
            if(line in fangji_set):
                name = line.replace("\n","")
            if line.startswith("《"):
                source = line.replace("\n","")
            if line.startswith("【组成】"):
                detail = line
                line = fangjifile.readline()
                while line.startswith("【") == False:
                    detail += line
                    line = fangjifile.readline()
                detail = detail.replace("\u3000","").replace("\n","")
            if line.startswith("【用法】"):
                use = line
                line = fangjifile.readline()
                while line.startswith("【") == False:
                    use += line
                    line = fangjifile.readline()
                use = use.replace("\u3000","").replace("\n","")
            if line.startswith("【功用】"):
                function = line
                line = fangjifile.readline()
                while line.startswith("【") == False:
                    function += line
                    line = fangjifile.readline()
                function = function.replace("\u3000","").replace("\n","")
            if line.startswith("【主治】"):
                fix = line
                line = fangjifile.readline()
                while line.startswith("【") == False:
                    fix += line
                    line = fangjifile.readline()
                fix = fix.replace("\u3000","").replace("\n","")
                list.append({
                    "name": name,
                    "source": source,
                    "detail": detail,
                    "use": use,
                    "function": function,
                    "fix": fix
                })
                continue
            else:
                line = fangjifile.readline()
        print("方剂数量：%s " % len(list))
        df = pd.DataFrame(list)
        xlsx_path = '/Users/feidao/Documents/me/note/development/vue/vue-learning/yixin-backend/database/basic.xlsx'
        with pd.ExcelWriter(xlsx_path, mode="a", if_sheet_exists="replace") as writer:
        # with pd.ExcelWriter('basic.xlsx') as writer:
            df.to_excel(writer, sheet_name='fangji', index=False)



def content_handle():
    xlsx_path = '/Users/feidao/Documents/me/note/development/vue/vue-learning/yixin-backend/database/basic.xlsx'
    df = pd.read_excel(xlsx_path, sheet_name="zhongyao2")
    df['desc'] = df['desc'].str.replace("　", "")
    # df['function'] = df['function'].str.replace("\n","").str.replace(" ","")
    # df['source']=  df['source'].str.replace("\n","").str.replace(" ","")
    # df.drop(df.filter(regex="Unnamed"),axis=1, inplace=True)
    # 追加需要用 mode = a
    with pd.ExcelWriter(xlsx_path, mode="a", if_sheet_exists="replace") as writer:
        # with pd.ExcelWriter('basic.xlsx') as writer:
        df.to_excel(writer, sheet_name='zhongyao', index=False)


if __name__ == '__main__':
    # read_pdf("/Users/feidao/Documents/me-book/中医药十三五教材/中药学.pdf")
    # read_txt_file("convertedFile.txt")
    # content_handle()
    # read_fangji_pdf("/Users/feidao/Documents/me-book/中医药十三五教材/方剂学.pdf")
    read_fangjixue_txt()
